<?php

namespace app\controller\crm;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

/**
 * 订单审核管理控制器
 */
class OrderReview extends BaseController
{
    /**
     * 获取订单审核列表
     */
    public function list()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $status = $params['status'] ?? '';
        $businessType = $params['business_type'] ?? ''; // 业务类型
        $reviewType = $params['review_type'] ?? ''; // 审核类型
        $keyword = $params['keyword'] ?? '';
        
        $query = Db::name('crm_order_review')
            ->alias('r')
            ->field('r.*, c.name as customer_name, u.name as user_name')
            ->leftJoin('crm_customer c', 'r.customer_id = c.id')
            ->leftJoin('admin u', 'r.user_id = u.id');
        
        if ($status !== '') {
            $query->where('r.status', $status);
        }
        
        if ($businessType !== '') {
            $query->where('r.business_type', $businessType);
        }
        
        if ($reviewType !== '') {
            $query->where('r.review_type', $reviewType);
        }
        
        if ($keyword) {
            $query->where(function($q) use ($keyword) {
                $q->where('c.name', 'like', "%{$keyword}%")
                  ->whereOr('r.order_no', 'like', "%{$keyword}%");
            });
        }
        
        $total = $query->count();
        $list = $query->order('r.create_time', 'desc')
            ->page($page, $limit)
            ->select();
        
        // 格式化数据
        $list = $list ? $list->toArray() : [];
        foreach ($list as &$item) {
            $item['business_type_text'] = $this->getBusinessTypeText($item['business_type']);
            $item['review_type_text'] = $this->getReviewTypeText($item['review_type']);
            $item['status_text'] = $this->getStatusText($item['status']);
            
            // 解析附件JSON
            if ($item['attachment']) {
                $item['attachment'] = json_decode($item['attachment'], true);
            }
        }
        
        return $this->paginate($list, $total, (int)$page, (int)$limit);
    }
    
    /**
     * 获取审核详情
     */
    public function detail()
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;
        
        if (!$id) {
            return $this->error('参数错误');
        }
        
        $review = Db::name('crm_order_review')
            ->alias('r')
            ->field('r.*, c.name as customer_name, u.name as user_name, ru.name as reviewer_name')
            ->leftJoin('crm_customer c', 'r.customer_id = c.id')
            ->leftJoin('admin u', 'r.signer_id = u.id')
            ->leftJoin('admin ru', 'r.reviewer_id = ru.id')
            ->where('r.id', $id)
            ->find();
        
        if (!$review) {
            return $this->error('审核记录不存在');
        }
        
        // 解析JSON数据
        $review['original_data'] = $review['original_data'] ? json_decode($review['original_data'], true) : null;
        $review['new_data'] = $review['new_data'] ? json_decode($review['new_data'], true) : null;
        $review['attachment'] = $review['attachment'] ? json_decode($review['attachment'], true) : [];
        
        $review['business_type_text'] = $this->getBusinessTypeText($review['business_type']);
        $review['review_type_text'] = $this->getReviewTypeText($review['review_type']);
        $review['status_text'] = $this->getStatusText($review['status']);
        
        return $this->success($review, '获取成功');
    }
    
    /**
     * 提交订单审核申请
     */
    public function submit()
    {
        $params = Request::param();
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        // 获取用户名称
        $userInfo = Db::name('admin')->field('name')->where('id', $userId)->find();
        
        // 准备审核数据
        $reviewData = [
            'order_id' => $params['order_id'] ?? 0,
            'customer_id' => $params['customer_id'] ?? 0,
            'order_no' => $params['order_no'] ?? '',
            'business_type' => $params['business_type'] ?? 1,
            'review_type' => $params['review_type'] ?? 1,
            'amount' => $params['amount'] ?? 0,
            'original_data' => isset($params['original_data']) ? json_encode($params['original_data']) : '',
            'new_data' => isset($params['new_data']) ? json_encode($params['new_data']) : '',
            'attachment' => isset($params['attachment']) ? json_encode($params['attachment']) : '',
            'status' => 1, // 待审核
            'user_id' => $userId,
            'user_name' => $userInfo['name'] ?? '',
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        $reviewId = Db::name('crm_order_review')->insertGetId($reviewData);
        
        if ($reviewId) {
            return $this->success('审核申请已提交');
        }
        
        return $this->error('提交失败');
    }
    
    /**
     * 审核处理（通过/驳回）
     */
    public function approve()
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;
        $status = $params['status'] ?? 2; // 2-通过 3-驳回
        $remark = $params['remark'] ?? '';
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        if (!in_array($status, [2, 3])) {
            return $this->error('审核状态参数错误');
        }
        
        // 检查权限（只有超级管理员和部门经理可以审核）
        $userInfo = Db::name('admin')
            ->field('id, name, group_id')
            ->where('id', $userId)
            ->find();
        
        if (!$userInfo || $userInfo['group_id'] > 2) {
            return $this->error('无审核权限');
        }
        
        $review = Db::name('crm_order_review')->where('id', $id)->find();
        
        if (!$review) {
            return $this->error('审核记录不存在');
        }
        
        if ($review['status'] != 1) {
            return $this->error('该审核已处理');
        }
        
        Db::startTrans();
        try {
            // 更新审核状态
            Db::name('crm_order_review')->where('id', $id)->update([
                'status' => $status,
                'reviewer_id' => $userId,
                'reviewer_name' => $userInfo['name'],
                'review_time' => date('Y-m-d H:i:s'),
                'review_remark' => $remark,
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            // 如果审核通过，执行相应的业务逻辑
            if ($status == 2) {
                $this->processApprovedReview($review);
            }
            
            Db::commit();
            return $this->success($status == 2 ? '审核通过' : '审核已驳回');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('审核失败：' . $e->getMessage());
        }
    }
    
    /**
     * 处理审核通过的业务逻辑
     */
    private function processApprovedReview($review)
    {
        // 根据不同的审核类型执行不同的操作
        switch ($review['review_type']) {
            case 1: // 到账审核
                // 更新订单付款状态
                if ($review['order_id'] > 0) {
                    Db::name('crm_order')->where('id', $review['order_id'])->update([
                        'payment_status' => 3, // 已付款
                        'update_time' => time()
                    ]);
                }
                break;
            
            case 2: // 合同回收审核
                // 更新合同状态
                if ($review['order_id'] > 0) {
                    Db::name('crm_order')->where('id', $review['order_id'])->update([
                        'contract_status' => 2, // 已签订
                        'update_time' => time()
                    ]);
                }
                break;
            
            case 3: // 开票审核
                // 创建发票记录（如果有发票管理模块）
                // 这里可以扩展发票相关的逻辑
                break;
        }
    }
    
    /**
     * 获取业务类型文本
     */
    private function getBusinessTypeText($type)
    {
        $texts = [
            1 => '案件委托',
            2 => '诉讼指导',
            3 => '法务顾问套餐',
            4 => '非诉专项',
            5 => '律师函',
            6 => '开具发票'
        ];
        return $texts[$type] ?? '未知';
    }
    
    /**
     * 获取审核类型文本
     */
    private function getReviewTypeText($type)
    {
        $texts = [
            1 => '到账审核',
            2 => '合同回收审核',
            3 => '开票审核'
        ];
        return $texts[$type] ?? '未知';
    }
    
    /**
     * 获取审核状态文本
     */
    private function getStatusText($status)
    {
        $texts = [
            1 => '待审核',
            2 => '审核通过',
            3 => '审核驳回'
        ];
        return $texts[$status] ?? '未知';
    }
    
    /**
     * 获取业务类型选项
     */
    public function businessTypeOptions()
    {
        $options = [
            ['value' => 1, 'label' => '案件委托'],
            ['value' => 2, 'label' => '诉讼指导'],
            ['value' => 3, 'label' => '法务顾问套餐'],
            ['value' => 4, 'label' => '非诉专项'],
            ['value' => 5, 'label' => '律师函'],
            ['value' => 6, 'label' => '开具发票']
        ];
        
        return $this->success($options, '获取成功');
    }
    
    /**
     * 获取审核类型选项
     */
    public function reviewTypeOptions()
    {
        $options = [
            ['value' => 1, 'label' => '到账审核'],
            ['value' => 2, 'label' => '合同回收审核'],
            ['value' => 3, 'label' => '开票审核']
        ];
        
        return $this->success($options, '获取成功');
    }
    
    /**
     * 获取审核统计信息
     */
    public function statistics()
    {
        $userId = $this->getUserId();
        
        // 订单审核统计
        $orderStats = Db::name('crm_order_review')
            ->field('status, review_type, COUNT(*) as count, SUM(amount) as total_amount')
            ->group('status, review_type')
            ->select()
            ->toArray();
        
        $stats = [
            'pending' => 0,
            'approved' => 0,
            'rejected' => 0,
            'total' => 0,
            'total_amount' => 0,
            'by_review_type' => []
        ];
        
        foreach ($orderStats as $item) {
            if ($item['status'] == 1) $stats['pending'] += $item['count'];
            if ($item['status'] == 2) {
                $stats['approved'] += $item['count'];
                $stats['total_amount'] += $item['total_amount'];
            }
            if ($item['status'] == 3) $stats['rejected'] += $item['count'];
            $stats['total'] += $item['count'];
            
            $reviewTypeText = $this->getReviewTypeText($item['review_type']);
            if (!isset($stats['by_review_type'][$reviewTypeText])) {
                $stats['by_review_type'][$reviewTypeText] = [
                    'pending' => 0,
                    'approved' => 0,
                    'rejected' => 0,
                    'total' => 0
                ];
            }
            
            if ($item['status'] == 1) $stats['by_review_type'][$reviewTypeText]['pending'] += $item['count'];
            if ($item['status'] == 2) $stats['by_review_type'][$reviewTypeText]['approved'] += $item['count'];
            if ($item['status'] == 3) $stats['by_review_type'][$reviewTypeText]['rejected'] += $item['count'];
            $stats['by_review_type'][$reviewTypeText]['total'] += $item['count'];
        }
        
        return $this->success($stats, '获取成功');
    }
}
